package com.casework

import org.jets3t.service.acl.AccessControlList
import org.jets3t.service.impl.rest.httpclient.RestS3Service
import org.jets3t.service.model.S3Bucket
import org.jets3t.service.model.S3Object
import org.jets3t.service.security.AWSCredentials

class AmazonS3Service {

    static String accessKey = "asdfasdfa"
    static String secretKey = "E/bTILeOmXe+asdfasdf/6J"
    static RestS3Service s3 = new RestS3Service(new AWSCredentials(accessKey, secretKey))
    boolean transactional = false
    String defaultBucketLocation = S3Bucket.LOCATION_EUROPE

    Map mimeExtensionMap = [
            "png": "image/png",
            "jpg": "image/jpeg",
            "gif": "image/gif",
            "tiff": "image/tiff",
            "pdf": "application/pdf",
            "mpeg": "video/mpeg",
            "mp4": "video/mp4",
            "mov": "video/quicktime",
            "wmv": "video/x-ms-wmv",
            "html": "text/html",
            "xml": "text/xml",
            "mp3": "audio/mpeg",
            "flv": "application/octet-stream"
    ]

    S3Bucket makeBucket() {
        def baseBucket = s3.getOrCreateBucket("casework-files", defaultBucketLocation)
        baseBucket.setAcl AccessControlList.REST_CANNED_PUBLIC_READ
        return baseBucket
    }

    void put(inputstream, name, uid, ext, length) {
        if (mimeExtensionMap.containsKey(ext.toLowerCase())) {
            String mime = mimeExtensionMap[ext.toLowerCase()];
            S3Bucket bucket = makeBucket()
            S3Object up = new S3Object()
            up.setAcl AccessControlList.REST_CANNED_PUBLIC_READ
            up.setContentLength length
            up.setContentType mime
            up.setDataInputStream inputstream
            up.setKey "files/$name"
            up.setBucketName bucket.getName()
            s3.putObject bucket, up
        }
    }

}
